<template>
  <div >
    <Treeselect
      v-model="initValue"
      :options="treeData"
      :disabled="disabled"
      no-results-text="无数据"
      :normalizer="normalizer"
      no-options-text="无数据"
      :style="{width:width}"
      :default-expand-level="2"
      placeholder="根目录"
      @select="select"
    />
  </div>
</template>

<script>
  import request from '@/utils/request'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { Notification } from 'element-ui'

  export default {
    components: { Treeselect },
    props: {
      form: {
        type: Object,
        default: () => {
          return null
        }
      },
      /* 编辑时的初始值 */
      initValue: {
        type: Number,
        default: null
      },
      /* 关键字 */
      keyword: {
        type: String,
        default: ''
      },
      width: {
        type: String,
        default: '100%'
      },
      url: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        treeData: [],
        normalizer(node) {
          if (node.children == null || node.children === 'null') {
            delete node.children
          }
          return {
            id: node.id,
            label: node.label ? node.label : node.name,
            children: node.children
          }
        }
      }
    },
    created() {
      this.remoteMethod('')
    },
    methods: {
      // 请求获取商品数据接口
      ajaxGoods() {
        return request({
          url: 'api/jtgDropDown/supplierTypeTree',
          method: 'GET'
        })
      },
      // 获取远程数据并赋值
      remoteMethod(data) {
        this.ajaxGoods(data).then(res => {
          if (res) {
            this.treeData = res.content ? res.content : res
            this.treeData.push({ id: 0, label: '根目录' })
            this.treeData.sort(
              (pre, cur) =>
                pre.id - cur.id
            )
          }
        }).catch(e => {
          this.treeData = []
          this.totalnum = 0
          Notification.error({
            title: '数据请求失败',
            duration: 5000
          })
        })
      },
      select(node) {
        this.form[this.keyword] = node.id
        this.$emit('change', node)
      }
    }
  }
</script>

